/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.CoolingSystem;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.Isle;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class CoolingSystemJpaController implements Serializable {

    public CoolingSystemJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }
    public CoolingSystemJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(CoolingSystem coolingSystem) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (coolingSystem.getIsleCollection() == null) {
            coolingSystem.setIsleCollection(new ArrayList<Isle>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = coolingSystem.getComponent();
        if (componentOrphanCheck != null) {
            CoolingSystem oldCoolingSystemOfComponent = componentOrphanCheck.getCoolingSystem();
            if (oldCoolingSystemOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type CoolingSystem whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Component component = coolingSystem.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                coolingSystem.setComponent(component);
            }
            Collection<Isle> attachedIsleCollection = new ArrayList<Isle>();
            for (Isle isleCollectionIsleToAttach : coolingSystem.getIsleCollection()) {
                isleCollectionIsleToAttach = em.getReference(isleCollectionIsleToAttach.getClass(), isleCollectionIsleToAttach.getId());
                attachedIsleCollection.add(isleCollectionIsleToAttach);
            }
            coolingSystem.setIsleCollection(attachedIsleCollection);
            em.persist(coolingSystem);
            if (component != null) {
                component.setCoolingSystem(coolingSystem);
                component = em.merge(component);
            }
            for (Isle isleCollectionIsle : coolingSystem.getIsleCollection()) {
                CoolingSystem oldIDCoolingSystemOfIsleCollectionIsle = isleCollectionIsle.getIDCoolingSystem();
                isleCollectionIsle.setIDCoolingSystem(coolingSystem);
                isleCollectionIsle = em.merge(isleCollectionIsle);
                if (oldIDCoolingSystemOfIsleCollectionIsle != null) {
                    oldIDCoolingSystemOfIsleCollectionIsle.getIsleCollection().remove(isleCollectionIsle);
                    oldIDCoolingSystemOfIsleCollectionIsle = em.merge(oldIDCoolingSystemOfIsleCollectionIsle);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCoolingSystem(coolingSystem.getId()) != null) {
                throw new PreexistingEntityException("CoolingSystem " + coolingSystem + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(CoolingSystem coolingSystem) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            CoolingSystem persistentCoolingSystem = em.find(CoolingSystem.class, coolingSystem.getId());
            Component componentOld = persistentCoolingSystem.getComponent();
            Component componentNew = coolingSystem.getComponent();
            Collection<Isle> isleCollectionOld = persistentCoolingSystem.getIsleCollection();
            Collection<Isle> isleCollectionNew = coolingSystem.getIsleCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                CoolingSystem oldCoolingSystemOfComponent = componentNew.getCoolingSystem();
                if (oldCoolingSystemOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type CoolingSystem whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                coolingSystem.setComponent(componentNew);
            }
            Collection<Isle> attachedIsleCollectionNew = new ArrayList<Isle>();
            for (Isle isleCollectionNewIsleToAttach : isleCollectionNew) {
                isleCollectionNewIsleToAttach = em.getReference(isleCollectionNewIsleToAttach.getClass(), isleCollectionNewIsleToAttach.getId());
                attachedIsleCollectionNew.add(isleCollectionNewIsleToAttach);
            }
            isleCollectionNew = attachedIsleCollectionNew;
            coolingSystem.setIsleCollection(isleCollectionNew);
            coolingSystem = em.merge(coolingSystem);
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setCoolingSystem(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setCoolingSystem(coolingSystem);
                componentNew = em.merge(componentNew);
            }
            for (Isle isleCollectionOldIsle : isleCollectionOld) {
                if (!isleCollectionNew.contains(isleCollectionOldIsle)) {
                    isleCollectionOldIsle.setIDCoolingSystem(null);
                    isleCollectionOldIsle = em.merge(isleCollectionOldIsle);
                }
            }
            for (Isle isleCollectionNewIsle : isleCollectionNew) {
                if (!isleCollectionOld.contains(isleCollectionNewIsle)) {
                    CoolingSystem oldIDCoolingSystemOfIsleCollectionNewIsle = isleCollectionNewIsle.getIDCoolingSystem();
                    isleCollectionNewIsle.setIDCoolingSystem(coolingSystem);
                    isleCollectionNewIsle = em.merge(isleCollectionNewIsle);
                    if (oldIDCoolingSystemOfIsleCollectionNewIsle != null && !oldIDCoolingSystemOfIsleCollectionNewIsle.equals(coolingSystem)) {
                        oldIDCoolingSystemOfIsleCollectionNewIsle.getIsleCollection().remove(isleCollectionNewIsle);
                        oldIDCoolingSystemOfIsleCollectionNewIsle = em.merge(oldIDCoolingSystemOfIsleCollectionNewIsle);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = coolingSystem.getId();
                if (findCoolingSystem(id) == null) {
                    throw new NonexistentEntityException("The coolingSystem with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            CoolingSystem coolingSystem;
            try {
                coolingSystem = em.getReference(CoolingSystem.class, id);
                coolingSystem.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The coolingSystem with id " + id + " no longer exists.", enfe);
            }
            Component component = coolingSystem.getComponent();
            if (component != null) {
                component.setCoolingSystem(null);
                component = em.merge(component);
            }
            Collection<Isle> isleCollection = coolingSystem.getIsleCollection();
            for (Isle isleCollectionIsle : isleCollection) {
                isleCollectionIsle.setIDCoolingSystem(null);
                isleCollectionIsle = em.merge(isleCollectionIsle);
            }
            em.remove(coolingSystem);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<CoolingSystem> findCoolingSystemEntities() {
        return findCoolingSystemEntities(true, -1, -1);
    }

    public List<CoolingSystem> findCoolingSystemEntities(int maxResults, int firstResult) {
        return findCoolingSystemEntities(false, maxResults, firstResult);
    }

    private List<CoolingSystem> findCoolingSystemEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(CoolingSystem.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public CoolingSystem findCoolingSystem(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(CoolingSystem.class, id);
        } finally {
            em.close();
        }
    }

    public int getCoolingSystemCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<CoolingSystem> rt = cq.from(CoolingSystem.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
